package com.ymt.bpm.service.engine.bpd.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ymt.bpm.dao.MDao;
import com.ymt.bpm.model.Const.Oplog;
import com.ymt.bpm.model.PBpdCatetree;
import com.ymt.bpm.model.POperationlog;
import com.ymt.bpm.service.engine.bpd.BpdCateService;
import com.ymt.bpm.service.platform.log.OpLogService;
import com.ymt.bpm.util.Const;
import com.ymt.bpm.util.DhxUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author Johnny
 * Created by Johnny on 2017/4/6.
 */
@Service
public class BpdCateServiceImpl implements BpdCateService {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    private String mapper = "PBpdCatetreeMapper";

    @Autowired
    private MDao mDao;

    @Autowired
    private OpLogService oplog;

    @Override
    public JSONArray getCateTree(String tenantId, String lang, int timezoneOffset) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put(Const.TENANT_ID, tenantId);
        List<PBpdCatetree> list = mDao.selectList(mapper, "getAllByTenant", paramMap);
        JSONArray rtn = new JSONArray();
        if (list!=null && list.size()>0) {
            for (PBpdCatetree c : list) {
                JSONObject o = DhxUtil.toFastJsonWithDate(c, lang, timezoneOffset);
                rtn.add(o);
            }
        }
        return rtn;
    }

    @Override
    public JSONObject saveCate(String tenantId, String loginName, String displayName, String ip, PBpdCatetree catetree) {
        JSONObject rtn = new JSONObject();
        int rs = 0;
        if (catetree.getId()==null || catetree.getId().length()==0) {
            if ("0".equals(catetree.gettType())) {
                catetree.setId("CATE-"+ UUID.randomUUID().toString());
                catetree.setTenantId(tenantId);
                rs = mDao.insert(mapper, "insert", catetree);
            }
        } else {
            rs = mDao.update(mapper, "updateByPrimaryKeySelective", catetree);
        }
        rtn.put("id", catetree.getId());
        rtn.put("result", rs);

        //记录操作日志
        oplog.bizlog(tenantId,
                loginName,
                displayName,
                ip,
                catetree.getId()==null ? Oplog.OP.CREATE : Oplog.OP.UPDATE,
                Oplog.CODE.PROCESS_BPDCATEGORY,
                catetree.getName());

        return rtn;
    }

    @Override
    public JSONObject delete(String tenantId, String loginName, String displayName, String ip, String id, String tType, boolean cascade) {
        PBpdCatetree catetree = new PBpdCatetree();
        catetree.setTenantId(tenantId);
        catetree.setId(id);
        catetree.settType(tType);
        catetree = mDao.selectOne(mapper, "selectByObj", catetree);
        int rs = 0;
        if (cascade) {
            rs = mDao.delete(mapper, "deleteAllChildren", catetree);
        } else {
            rs = mDao.delete(mapper, "deleteByObj", catetree);
        }
        JSONObject rtn = new JSONObject();
        rtn.put("result", rs);

        //记录操作日志
        oplog.bizlog(tenantId,
                loginName,
                displayName,
                ip,
                catetree.getId()==null ? Oplog.OP.CREATE : Oplog.OP.UPDATE,
                Oplog.CODE.PROCESS_BPDCATEGORY,
                catetree.getName());

        return rtn;
    }

    @Override
    public String checkName(String tenantId, String parentId, String name) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put(Const.TENANT_ID, tenantId);
        paramMap.put("parentId", parentId);
        paramMap.put("name", name);
        int count = mDao.selectOne(mapper, "checkName", paramMap);
        return count>0 ? Boolean.FALSE.toString() : Boolean.TRUE.toString();
    }

    @Override
    public JSONObject addBpdToCate(String tenantId, boolean check, PBpdCatetree catetree) {
        JSONObject rtn = new JSONObject();
        int rs = 0;
        catetree.setTenantId(tenantId);
        PBpdCatetree old = mDao.selectOne(mapper, "selectByObj", catetree);
        if (old!=null) {
            if (check) {
                rtn.put("msg", "exists");
                return rtn;
            } else {
                rs += mDao.delete(mapper, "deleteByObj", catetree);
            }
        }
        rs += mDao.insert(mapper, "insert", catetree);
        rtn.put("result", rs);
        return rtn;
    }

    @Override
    public JSONObject getBpdTreeDhx(String tenantId) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put(Const.TENANT_ID, tenantId);
        List<PBpdCatetree> list = mDao.selectList(mapper, "getAllByTenant", paramMap);
        JSONObject childrenMap = new JSONObject();
        for (PBpdCatetree cate : list) {
            JSONObject obj = new JSONObject();
            obj.put("id", cate.getId());
            obj.put("text", cate.getName());
            if (!childrenMap.containsKey(cate.getParentId())) {
                childrenMap.put(cate.getParentId(), new JSONArray());
            }
            childrenMap.getJSONArray(cate.getParentId()).add(obj);
        }
        JSONObject proot = new JSONObject();
        proot.put("id", "PROCESS_ROOT");
        proot.put("text", "PROCESS_ROOT");
        getChildren(proot, childrenMap);
        proot.put("id", "0");
        return proot;
    }

    private void getChildren(JSONObject root, JSONObject childrenMap) {
        JSONArray children = childrenMap.getJSONArray(root.getString("id"));
        if (children!=null && children.size()>0) {
            root.put("item", children);
            for (int i=0; i<children.size(); i++) {
                JSONObject child = children.getJSONObject(i);
                getChildren(child, childrenMap);
            }
        }
    }

}
